package com.yl.projects.ui

import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.yl.common.base.BaseVMFragment
import com.yl.common.exp.Constants
import com.yl.common.network.BaseResp
import com.yl.common.network.BaseStateObserver
import com.yl.common.util.ToastUtil
import com.yl.common.widget.LoadingViewUtil
import com.yl.projects.R
import com.yl.projects.adapter.ProjectChildAdapter
import com.yl.projects.adapter.ProjectChildItemClickListener
import com.yl.projects.bean.Project
import com.yl.projects.databinding.FragmentProjectChildBinding
import com.yl.projects.viewmodel.ProjectViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel

class ProjectChildFragment : BaseVMFragment<FragmentProjectChildBinding>() {

    var collectPosition: Int = 0

    companion object {
        private const val C_ID: String = "cid"
        private const val INDEX: String = "index"

        fun newInstance(cid: Int, index: Int): ProjectChildFragment {
            val f = ProjectChildFragment()
            val bundle = Bundle()
            bundle.putInt(C_ID, cid)
            bundle.putInt(INDEX, index)
            f.arguments = bundle
            return f
        }
    }

    private var currentID: Int = 0
    private var currentIndex: Int = 0

    private val projectViewModel: ProjectViewModel by viewModel()
    lateinit var projectChildAdapter: ProjectChildAdapter
    lateinit var lm: LinearLayoutManager
    var isLoadMore = false
    var list: MutableList<Project.ProjectDetail> = arrayListOf()

    override fun getLayoutID(): Int {
        return R.layout.fragment_project_child
    }

    override fun observe() {
        projectViewModel.proList.observe(this, object : BaseStateObserver<Project>(null) {
            override fun getRespDataSuccess(it: BaseResp<Project>) {

                resetUI()

                currentPage = it.data!!.curPage

                if (currentPage == 1) {
                    list.clear()
                }

                if (it.data!!.over) {
                    projectChildAdapter.isLastPage = true
                }

                list.addAll(it.data!!.datas)

                if (currentPage == 1) {
                    projectChildAdapter.setData(null)
                    projectChildAdapter.setData(list)
                    lm.scrollToPosition(0)
                } else {
                    projectChildAdapter.setData(list)
                }

                Log.d(TAG, "observe articleList: " + list.size)

            }

            override fun getRespDataEnd() {
                resetUI()
            }
        })


        projectViewModel.collectData.observe(this, object : BaseStateObserver<String>(null) {
            override fun getRespDataStart() {
                LoadingViewUtil.showLoadingDialog(requireContext(), true)
            }

            override fun getRespDataEnd() {
                LoadingViewUtil.dismissLoadingDialog()
            }

            override fun getRespSuccess() {
                LoadingViewUtil.dismissLoadingDialog()
                if (list[collectPosition].collect) {
                    ToastUtil.showMsg("取消收藏！")
                    list[collectPosition].collect = false
                } else {
                    ToastUtil.showMsg("收藏成功！")
                    list[collectPosition].collect = true
                }
                projectChildAdapter.notifyItemChanged(collectPosition)
            }
        })

    }

    override fun init() {
        val a = arguments
        if (a != null) {
            currentID = a.getInt(C_ID)
            currentIndex = a.getInt(INDEX)
        }

        lm = LinearLayoutManager(activity)
        mBind.recyclerView.layoutManager = lm
        projectChildAdapter = ProjectChildAdapter(object : ProjectChildItemClickListener {
            override fun onItemClick(position: Int) {
                val data = list[position]
                ARouter.getInstance()
                    .build(Constants.PATH_WEB)
                    .withString(Constants.WEB_LINK, data.link)
                    .withString(Constants.WEB_TITLE, data.title)
                    .navigation()
            }

            override fun onCollectClick(position: Int) {
                collectPosition = position
                if (list[collectPosition].collect) {
                    projectViewModel.unCollect(list[collectPosition].id)
                } else {
                    projectViewModel.collect(list[collectPosition].id)
                }
            }
        })

        mBind.recyclerView.adapter = projectChildAdapter

        mBind.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE && projectChildAdapter.itemCount != 0 &&
                    (lm.findLastVisibleItemPosition() + 1 == projectChildAdapter.itemCount &&
                            !isLoadMore && !projectChildAdapter.isLastPage)
                ) {
                    Log.d(TAG, "onScrollStateChanged: last-----")
                    isLoadMore = true
                    lazyLoad()
                }
            }
        })


        mBind.swiperefreshlayout.setColorSchemeResources(com.yl.common.R.color.theme_color)
        mBind.swiperefreshlayout.setOnRefreshListener {
            projectChildAdapter.isLastPage = false
            projectViewModel.getProjectChildList(1, currentID)
        }

    }

      fun scrollToTop() {
        mBind.recyclerView.run {
            if (lm.findFirstVisibleItemPosition() > 20) {
                scrollToPosition(0)
            } else {
                smoothScrollToPosition(0)
            }
        }
    }


    override fun lazyLoad() {
        projectViewModel.getProjectChildList(currentPage + 1, currentID)
    }

    private fun resetUI() {
        isLoadMore = false//加载更多完成，重置false
        if (mBind.swiperefreshlayout.isRefreshing) {
            mBind.swiperefreshlayout.isRefreshing = false
        }
    }

    //----------------------------------------------------------------

//    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
//        super.onViewCreated(view, savedInstanceState)
//        Log.d("pcf", "onViewCreated: F$currentIndex")
//    }
//
//    override fun onStart() {
//        super.onStart()
//        Log.d("pcf", "onStart: F$currentIndex")
//    }
//
//    override fun onResume() {
//        super.onResume()
//        Log.d("pcf", "onResume: F$currentIndex")
//    }
//
//    override fun onPause() {
//        super.onPause()
//        Log.d("pcf", "onPause: F$currentIndex")
//    }
//
//    override fun onStop() {
//        super.onStop()
//        Log.d("pcf", "onStop: F$currentIndex")
//    }
//
//    override fun onDestroyView() {
//        super.onDestroyView()
//        Log.d("pcf", "onDestroyView: F$currentIndex")
//    }
//
//    override fun onDestroy() {
//        super.onDestroy()
//        Log.d("pcf", "onDestroy: F$currentIndex")
//    }
//
//    override fun onDetach() {
//        super.onDetach()
//        Log.d("pcf", "onDetach: F$currentIndex")
//    }

}